package net.spatula.tally_ho.ui.validators;

/* Copyright 2006 Nicklas R Johnson
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

import java.util.List;

import net.spatula.tally_ho.utils.html.HtmlCleaner;
import net.spatula.tally_ho.utils.html.HtmlCleanerException;
import net.spatula.tally_ho.utils.html.HtmlDocumentCleanser;
import net.spatula.tally_ho.utils.html.HtmlDocumentCleanserException;
import wicket.markup.html.form.FormComponent;
import wicket.markup.html.form.validation.StringValidator;

public class HtmlCleanValidator extends StringValidator {

    private static final long serialVersionUID = 1L;

    public void onValidate(FormComponent component, String data) {

        System.out.println("component: " + component + ", data:" + data);
        if (data == null || data.length() < 2) {
            return;
        }

        String cleanedHtml = null;
        try {
            cleanedHtml = HtmlCleaner.clean(data);
        } catch (HtmlCleanerException e) {
            error(component);
        }

        System.out.println("Cleaned HTML:" + cleanedHtml);

        HtmlDocumentCleanser cleanser = new HtmlDocumentCleanser("p;br;a{href};em;strong;blockquote;body");

        String cleansedHtml = null;
        try {
            cleansedHtml = cleanser.cleanse("<body>" + cleanedHtml + "</body>");
            cleansedHtml = cleansedHtml.replaceAll("</?body>", "");
        } catch (HtmlDocumentCleanserException e) {
            List<String> errors = cleanser.getErrors();
            if (errors.size() > 0) {
                for (String error : errors) {
                    component.error("HTML parsing error:" + error);
                }
            } else {
                error(component);
            }
        }

        System.out.println("Cleansed HTML:" + cleansedHtml);

        if (cleanser.getCorrectionsCount() > 0) {
            List<String> errors = cleanser.getErrors();
            if (errors.size() > 0) {
                for (String error : errors) {
                    System.out.println(error);
                    component.error("HTML error:" + error);
                }
            }

        }

        if (cleansedHtml != null) {
            // component.setModelObject will truncate everything following the first semicolon.
            // god knows why
            component.getModel().setObject(component, cleansedHtml);
        }

    }

}
